import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: { },
  routes: constantRoutes // 默认是静态路由
}
const mutations = {
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  },
  setToken(state, token) {
    // 将token存储在vuex中 - 刷新会丢失
    state.token = token
    // 将token存储在本地中 - 持久化
    setToken(token)
  },
  // 退出功能
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}
const actions = {
  async login(context, data) {
    const result = await login(data)
    context.commit('setToken', result)
  },
  async getUserInfo(context, data) {
    // 发送获取用户资料的接口
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result
  },
  logout(context) {
    // 1. 删token
    context.commit('removeToken')
    // 2. 清用户信息
    context.commit('setUserInfo', {})
    // 3. 重置路由
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
